package chances.wechat.ctrl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import chances.epg.commons.utils.PathUtils;
import chances.epg.entity.user.WechatUser;
import chances.epg.session.UserSession;
import chances.epg.session.UserSessionHelper;
import chances.epg.user.service.WechatUserService;
import chances.wechat.config.WeChatMvcConfig;
import chances.wechat.log.WechatLogger;
import chances.wechat.model.WechatToken;
import chances.wechat.service.GatewayService;

public class LoginController implements ApplicationContextAware {

	static Logger logger = LoggerFactory.getLogger("login");

	@Autowired
	WechatUserService wechatUserService;
	
	@Autowired
	private GatewayService gatewayService;
	
	@Autowired
	protected WechatLogger wxLogger;

	@Autowired
	protected WeChatMvcConfig config;

	public static final String OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";

	public static final String LOGIN_BASE = "snsapi_base";
	public static final String LOGIN_USER_INFO = "snsapi_userinfo";

	protected String responseType = "code";
	
	protected ApplicationContext context;
	
	protected void login(HttpServletRequest request, HttpServletResponse response, String scope, String type,
			String state) throws IOException {
		String path = PathUtils.join(config.getEpgHost(),
				config.getBackPath(), type + ".wx");
		try {
			state = URLEncoder.encode(state, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		WechatToken token = gatewayService.getToken();
		
		StringBuffer sb = new StringBuffer(OAUTH_URL);
		sb.append("?appid=").append(token.getAppId()).append("&redirect_uri=").append(path).append("&response_type=")
				.append(responseType).append("&scope=").append(scope).append("&state=").append(state)
				.append("#wechat_redirect");
		
		response.sendRedirect(sb.toString());
	}
	
	/*protected void login(HttpServletRequest request, HttpServletResponse response, String scope, String type,
			String state) throws IOException {
		String path = PathUtils.join(config.getEpgHost(), request.getServletContext().getContextPath(),
				config.getBackPath(), type + ".wx");
		try {
			state = URLEncoder.encode(state, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		StringBuffer sb = new StringBuffer(OAUTH_URL);
		sb.append("?appid=").append(config.getAppId()).append("&redirect_uri=").append(path).append("&response_type=")
				.append(responseType).append("&scope=").append(scope).append("&state=").append(state)
				.append("#wechat_redirect");
		response.sendRedirect(sb.toString());
	}*/


	protected WechatUser back(HttpServletRequest request, HttpServletResponse response, String code, String state,
			String type) throws IOException {
		
		WechatUser wechatUser = gatewayService.login(code, state, type);
		WechatToken token = gatewayService.getToken();
		/*if(!state.startsWith("http://")) {
			gatewayService.proxy(request, response, "/qr/scanUpdate");
		}*/
		
		if(wechatUser.getOpenId()==null){
			return wechatUser;
		}
		
		UserSession userSession = (UserSession) UserSessionHelper.getUserSession(request);
		if(userSession != null) {
			userSession.setWechatUser(wechatUser);
			userSession.setUserId(wechatUser.getOpenId());
			userSession.setGuest(false);
		} else {
			userSession = new UserSession(wechatUser.getOpenId(), token.getToken());
			userSession.setCreateTime(System.currentTimeMillis());
			userSession.setLastActiveTime(System.currentTimeMillis());
			userSession.setWechatUser(wechatUser);
			userSession.setGuest(false);
			UserSessionHelper.saveUserSessionToSession(request, userSession);
		}
		return wechatUser;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}

}
